package com.yuanjin.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import com.yuanjin.R;
import com.yuanjin.adapter.FriendShow_ImageAddAdapter;
import com.yuanjin.models.FriendsShowItem;
import com.yuanjin.util.AsyncTask_ImageUpload;
import com.yuanjin.util.FileUtils;
import com.yuanjin.util.MediaUtils;
import com.yuanjin.util.UploadDataThread;
import com.yuanjin.util.Yuanjin;

/**
 * @author zhan414 使用BaseAdaper实现模仿微信朋友圈分享图片的图片添加功能部分
 */
public class FriendShowUploadActivity extends Activity implements
		OnClickListener {
	private EditText tv_message;
	private Button topbar_rightUploadButton;
	private GridView gridview;
	// private ArrayList<HashMap<String, Object>> arrayList = new
	// ArrayList<HashMap<String, Object>>();
	private ArrayList<Object> bitmaplist;
	private FriendShow_ImageAddAdapter imAdapter;
	// private String username;
	private ArrayList<String> imagePathList;
	private SharedPreferences sp;
	private boolean addboolean = true;
	private int ilength = 0;// 存有效上传图片的张数

	// ///////////////////
	String srcPath;
	private String uploadImageUrl = "http://1.zhan414.sinaapp.com/?/index.php?c=yuanjin_friendshow&a=uploadfile";
	private String uploadMessageUrl = "http://1.zhan414.sinaapp.com/?/index.php?c=main&a=uploadmessage";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friendshowupload);
		topbar_rightUploadButton = (Button) findViewById(R.id.topbar_rightUploadButton);
		gridview = (GridView) findViewById(R.id.gv_uploadshowimages);
		tv_message = (EditText) findViewById(R.id.tv_uploadshowmessage);

		topbar_rightUploadButton.setVisibility(View.VISIBLE);
		topbar_rightUploadButton.setOnClickListener(this);

		dataInit();// 必要数据的初始化

		// 去掉gridview的滚动效果
		gridview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// Log.e("test",
				// "------------>"+(MotionEvent.ACTION_MOVE==event.getAction()));
				return MotionEvent.ACTION_MOVE == event.getAction() ? true
						: false;
			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

				if (addboolean && position == bitmaplist.size() - 1) {
					// ((ImageView)view).setImageDrawable(R.drawable.ic_addgray);
					Log.e("test",
							parent.getChildAt(position).findViewById(
									R.id.gv_itemImage)
									+ "");
					Intent intent = new Intent(Intent.ACTION_PICK, null);
					intent.setDataAndType(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							"image/*");
					startActivityForResult(intent, Yuanjin.ALBUM_OK);
				}
				if (position != bitmaplist.size() - 1) {
					Intent intent = new Intent(FriendShowUploadActivity.this,
							PictureFlipperActivity.class);

					intent.putExtra("position", position);
					startActivity(intent);
					Log.e("TEST", "------------position--->" + position);

				}
			}

		});

	}

	private void dataInit() {
		/******************* 获取用户名 *********************/
		sp = getSharedPreferences(Yuanjin.YuanjinSharedPreference,
				Activity.MODE_PRIVATE);
		// username = sp.getString("username",
		// "username" + System.currentTimeMillis() / 1000);// 获取用户名
		// imagePathList = new ArrayList<String>();// 保存图片路径的list
		/****************************************/
		bitmaplist = new ArrayList<Object>();

		bitmaplist = Yuanjin.imageListCache;
		Object object = R.drawable.ic_addgray_light;
		bitmaplist.add(object);

		imAdapter = new FriendShow_ImageAddAdapter(this, bitmaplist);
		gridview.setAdapter(imAdapter);

		// intent操作要在setadapter的后边
		Intent intent = getIntent();
		srcPath = intent.getStringExtra("srcPath");
		imagePathList = Yuanjin.imagePathList;
		imagePathList.add(FileUtils.getImageName(srcPath));
		Log.e("test", "--------得到-srcPath--->" + srcPath);
		if (srcPath != null) {
			Bitmap bitmap = createPicture(srcPath);
			addPicture1(bitmap);
		}
	}

	/**
	 * @param srcPath
	 *            图片的路径 -- 生成经压缩后的可上传服务器的图片
	 */
	private Bitmap createPicture(String srcPath) {
		// 压缩图片地址
		String savePath = Environment.getExternalStorageDirectory().toString()
				+ "/yuanjinImage/cache/UploadFriendShowImage/";
		File out = new File(savePath);// 生成文件夹
		if (!out.exists()) {
			out.mkdirs();
		}
		long time = System.currentTimeMillis() / 1000;
		String username = sp.getString("username", "username" + time);// 获取用户名

		savePath = savePath + username + time + ".jpg";
		// imagePathList.add(savePath);// 保存压缩图片的地址
		Log.e("test", "------savePath-------->> " + savePath);

		// 生成压缩的图片
		Bitmap bitmap = MediaUtils.saveMediaThumbnail_normal(
				MediaUtils.MyMedia_Image, srcPath, savePath);
		return bitmap;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.topbar_rightUploadButton:
			// 获取图片的有效张数
			if (bitmaplist.get(bitmaplist.size() - 1) instanceof Bitmap) {
				ilength = bitmaplist.size();
			} else {
				ilength = bitmaplist.size() - 1;
			}
			for (int i = 0; i < ilength; i++) {
				AsyncTask_ImageUpload asyiu = new AsyncTask_ImageUpload(this,
						uploadImageUrl, imagePathList.get(i),
						(Bitmap) bitmaplist.get(i));
				// asyiu.execute("");//顺序执行
				asyiu.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ilength
						+ "");
			}
			// 图片路径array转string
			Log.e("-----test--->", "------imagePathList.toString()------>"
					+ imagePathList.toString());
			Log.e("-----test--->",
					"------imagePathList.toArray().toString()------>"
							+ imagePathList.toArray().toString());
			// 上传文字信息 - 用户id，发表时间（秒为单位），message，图片路径array（以后再加入点赞和评论）
			String imagePathString = imagePathList.toString();// 得到形如：[num1.jpg,
																// num2.jpg,
																// num3.jpg]的数据
			imagePathString = imagePathString.substring(1,
					imagePathString.length() - 1);// =>num1.jpg, num2.jpg,
													// num3.jpg
			Map<String, String> map = new HashMap<String, String>();
			map.put("username", Yuanjin.username);
			map.put("time", System.currentTimeMillis() / 1000 + "");
			map.put("message", tv_message.getText().toString());
			map.put("imagearray", imagePathString);

			JSONObject object = new JSONObject();
			Log.e("testing", "---username-->" + map.get("username"));
			Log.e("testing", "---time-->" + map.get("time"));
			Log.e("testing", "---message-->" + map.get("message"));
			Log.e("testing", "---imagearray-->" + map.get("imagearray"));
			UploadDataThread udt = new UploadDataThread(uploadMessageUrl, map);
			udt.start();// 开启上传线程

			// ************************ testing ******************8//
			Yuanjin.test_message=tv_message.getText().toString();
			Yuanjin.test_name=Yuanjin.username;
			FriendsShowItem showItem=new FriendsShowItem(Yuanjin.test_name, Yuanjin.test_message, null);
			Yuanjin.friendsShowItemList.add(1, showItem);

			break;

		default:
			break;
		}
	}

	// private void addPicture() {
	// Object object = new Object();
	// object = R.drawable.ic_camera;
	// bitmaplist.add(bitmaplist.size() - 1, object);
	// imAdapter.notifyDataSetChanged();
	// }

	private void addPicture1(Bitmap bitmap) {
		Object object = new Object();
		object = bitmap;
		if (bitmaplist.size() != 9) {
			bitmaplist.add(bitmaplist.size() - 1, object);
		} else {
			bitmaplist.set(bitmaplist.size() - 1, object);
			addboolean = false;
		}

		imAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Yuanjin.ALBUM_OK && data != null) {
			Uri uri = data.getData();
			String srcpathString = MediaUtils.getImageAbsolutePath(this, uri);
			imagePathList.add(FileUtils.getImageName(srcpathString));// 保存图片名称
			Bitmap bitmap = createPicture(srcpathString);
			if (bitmap != null) {
				addPicture1(bitmap);
			} else {
				Toast.makeText(this, "添加图片不成功", Toast.LENGTH_SHORT).show();
			}

		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		if (bitmaplist.size() != 1) {
			for (int i = 0; i < bitmaplist.size() - 1; i++) {
				if (bitmaplist.get(i) instanceof Bitmap) {
					((Bitmap) bitmaplist.get(i)).recycle();
				}

			}
		}
		Yuanjin.uploadNum = 0;// 清零
		bitmaplist.clear();
		imagePathList.clear();

		System.gc();

	}

}
